package auth.realm;


import auth.service.UserService;
import com.woniuxy.common.constant.UserConstant;
import com.woniuxy.common.entity.CenterUser;
import lombok.Setter;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

public class MyRealm extends AuthorizingRealm {
    @Resource
    @Setter
    private ApplicationContext ac;
    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //检索权限
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 返回认证信息
        //获取用户输入的账号
        Object phone = token.getPrincipal();
        //检索数据库，判断账号是否存在
        CenterUser user = userService.findUser(phone.toString());
        if (user == null) {
            //用户不存在
            return null;
        }else if(user.getCenterAccountstatus()==UserConstant.REGISTRY_NOT_CREDENTIAL){
            //注册未认证
            throw new LockedAccountException();
        }else if(user.getCenterAccountstatus()==UserConstant.SUSPENDED_ACCOUNT){
            //已被封号
            throw new DisabledAccountException();
        }
        //账号存在

        //屏蔽数据库密码验证，临时使用
        //String credentials =new String(((UsernamePasswordToken)token).getPassword());
        //credentials= new SimpleHash("MD5",credentials,"m",2).toString();

        ByteSource salt = ByteSource.Util.bytes(user.getSalt());
        SimpleAuthenticationInfo authenticationInfo =
                new SimpleAuthenticationInfo(phone, user.getPassword(), salt, this.getName());
        return authenticationInfo;

    }
}
